//
//  LiveListViewController.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2024/6/16.
//

#import "LiveListViewController.h"
#import "TableViewCell.h"
#import "LiveRoomViewController.h"
#import "AFNetworking.h"
#import "NewRoomEditVController.h"
#import <MJRefresh/MJRefresh.h>
#import "RoomSettingVC.h"
#import "LiveGoodsViewController.h"
#import "RYAlertController.h"
#import "SGQRCode.h"
#import "LiveStreamingData.h"

#import "LiveListShareView.h"

#import "LiveListSignInView.h"

#import "SignInSetBottomVIew.h"
/**
 加载数据的方式
 */
typedef enum : NSUInteger {
    DataLoadTypeNews, // 刷新数据
    DataLoadTypeMore, // 加载更多
} DataLoadType;

@interface LiveListViewController ()<UITableViewDelegate,UITableViewDataSource,toCheckCreateCourseDelegate,ButtonsActionDelegate,LiveListSignInDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIButton *nCLive;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UIButton *selectedButton;
@property (nonatomic, strong)LiveGoodsViewController *liveGoodsVC;
/** 当前页码     如果不填则默认为1 */
@property (nonatomic, assign) int page;
@property (nonatomic, assign) BOOL isToday;
@property (nonatomic, assign) BOOL isAgoraBeauty;
@property (nonatomic, assign) int version_id;//彩票 = 18，
///背景无数据
@property (nonatomic, strong) UIView *bgEmptyView;

@property (nonatomic, strong) UIButton *todayButton;
@property (nonatomic, strong) UIButton *allButton;
@property (nonatomic, strong) ResultModel *resultModel;
@property (nonatomic, assign) NSInteger buttonTag;
@end

@implementation LiveListViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:true];
    
//    [self updateButtonSelection];
    
//    [self setupAllRefreshData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isToday = true;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
    self.isAgoraBeauty = 0;
    [self navLeftButtons];
    
    self.dataArray = [NSMutableArray new];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    float viewWidth = (SCREEN_WIDTH-30);
    self.tableView.showsVerticalScrollIndicator = false;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = viewWidth*0.85;
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    self.tableView.backgroundColor = [UIColor clearColor];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        
    }
//    if (@available(iOS 15.0, *)) {
//        self.tableView.sectionHeaderTopPadding = 0;
//    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
     CAGradientLayer *gradientLayer = [CAGradientLayer layer];
     gradientLayer.frame = view.bounds;
     UIColor *startColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    UIColor *endColor = RYColorForHex(@"#f5f6fa");
     CGColorRef startColorRef = [startColor CGColor];
     CGColorRef endColorRef = [endColor CGColor];
     gradientLayer.startPoint = CGPointMake(0.5, 0.0);
     gradientLayer.endPoint = CGPointMake(0.5, 1.0);
     gradientLayer.colors = @[(__bridge id)startColorRef, (__bridge id)endColorRef];
     [view.layer insertSublayer:gradientLayer atIndex:0];
     self.tableView.backgroundView = view;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(YPW_kStatusBarHeight+kNavBarHeight);
    }];
    
    _nCLive = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nCLive addTarget:self action:@selector(constructionAction) forControlEvents:UIControlEventTouchUpInside];
    [_nCLive setBackgroundImage:[UIImage imageNamed:@"newConst"] forState:UIControlStateNormal];
    [self.view addSubview:_nCLive];
    
    [_nCLive mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view).offset(-15);
        make.bottom.mas_equalTo(self.view).offset(-80);
        make.width.height.offset(80);
    }];
    
    [self.bgEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.view);
        make.height.equalTo(@(210));
        make.width.equalTo(@(196));
    }];
    
//    [[YouinRTCManager shardManager] getQiuNiuID:^(BOOL success, NSError * _Nullable error) {
//    }];
//
    [self getEnterPriseId];
    
    [self setupAllRefreshData];
    
    
    
    
}

- (void)getEnterPriseId
{
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    NSDictionary *dic = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@v1/enterprise/enterprise_info/",HTTPSURL];
    __weak typeof(self) weakSelf = self;

    [manager GET:urlString parameters:nil headers:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"code"] intValue] == 200)
        {
            weakSelf.version_id = [responseObject[@"result"][@"version_id"] intValue];
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setInteger:weakSelf.version_id forKey:@"version_id"];
            [defaults synchronize];
        }else{
            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)navLeftButtons
{
    // 创建左侧按钮1
    self.todayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.todayButton setTitle:@"今日直播" forState:UIControlStateNormal];
    self.todayButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.todayButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.todayButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateSelected];
    [self.todayButton addTarget:self action:@selector(buttonsTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.todayButton.tag = 1000;
    // 默认选中今日直播
    self.selectedButton = self.todayButton;
    self.selectedButton.selected = YES;
//    self.selectedButton = self.todayButton;
       
   // 创建左侧按钮2
    self.allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.allButton setTitle:@"全部直播" forState:UIControlStateNormal];
    self.allButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.allButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.allButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateSelected];
    [self.allButton addTarget:self action:@selector(buttonsTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.allButton.tag = 1001;
    // 设置导航栏的左侧按钮
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:self.todayButton],
                                                 [[UIBarButtonItem alloc] initWithCustomView:self.allButton]];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button3 setImage:[UIImage imageNamed:@"rc_setting"] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(settingButtonsTapped) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:button3]
                                                 ];
}

- (void)constructionAction
{
    NewRoomEditVController *newVC = [[NewRoomEditVController alloc] init];
    newVC.delegate = self;
    [self.navigationController pushViewController:newVC animated:YES];
}
///今日，全部直播
- (void)buttonsTapped:(UIButton *)sender{
    self.selectedButton.selected = NO;
    sender.selected = YES;
    self.selectedButton = sender;
    self.page = 1;
    if (sender.tag == 1000) {
        self.isToday = true;
    }else{
        self.isToday = false;
    }
    [self setupAllRefreshData];
}

//- (void)updateButtonSelection
//{
//    self.selectedButton.selected = NO;
//       if (self.isToday) {
//           self.todayButton.selected = YES;
//           self.selectedButton = self.todayButton;
//       } else {
//           self.allButton.selected = YES;
//           self.selectedButton = self.allButton;
//       }
//}
///设置
- (void)settingButtonsTapped
{
    RoomSettingVC *settingVC = [[RoomSettingVC alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
}

- (void)setupAllRefreshData {
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf listDataRequestWithDataLoadType:DataLoadTypeNews];
    }];
    self.tableView.mj_header.ignoredScrollViewContentInsetTop = self.tableView.contentInset.top;
    
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page += 1;
        [weakSelf listDataRequestWithDataLoadType:DataLoadTypeMore];
    }];
}


- (void)listDataRequestWithDataLoadType:(DataLoadType)dataLoadType {
    __weak __typeof(self) weakSelf = self;
    [[YouinRTCManager shardManager] liveListCourse:self.page withIsToday:self.isToday success:^(id  _Nonnull json) {
        if (dataLoadType == DataLoadTypeNews) [weakSelf.tableView.mj_header endRefreshing];
        if (dataLoadType == DataLoadTypeMore) [weakSelf.tableView.mj_footer endRefreshing];
        LiveListModel *model = json;
        if (weakSelf.page == 1) {
            weakSelf.dataArray = [NSMutableArray new];
        }
        if (model.pages>=weakSelf.page) {
            
            NSArray *productDataModelArray = [NSArray array];
            if (model.result.count > 0) {
                productDataModelArray = model.result;
            } else {
                if (dataLoadType == DataLoadTypeMore) weakSelf.page -= 1;
            }
            
            // 下拉刷新数据
            if (dataLoadType == DataLoadTypeNews)
                weakSelf.dataArray = [productDataModelArray mutableCopy];
            if (dataLoadType == DataLoadTypeMore && productDataModelArray.count > 0) {
                [weakSelf.dataArray addObjectsFromArray:productDataModelArray];
            }
        }
        float footH = 0;
        if(model.pages>weakSelf.page) {
            [weakSelf.tableView.mj_footer resetNoMoreData];
        }
        else {
            footH = 40;
            [((MJRefreshAutoNormalFooter *)weakSelf.tableView.mj_footer) setTitle:@"已经到底啦～" forState:MJRefreshStateNoMoreData];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        weakSelf.tableView.contentInset = UIEdgeInsetsMake(weakSelf.tableView.contentInset.top, weakSelf.tableView.contentInset.left, footH, weakSelf.tableView.contentInset.right);
        if(weakSelf.dataArray.count == 0) {
            weakSelf.tableView.mj_footer.hidden = YES;
        }
        else {
            weakSelf.tableView.mj_footer.hidden = NO;
        }
        [weakSelf.tableView reloadData];
        
        weakSelf.bgEmptyView.hidden = YES;
        if (weakSelf.dataArray.count == 0) {
            weakSelf.bgEmptyView.hidden = NO;
           
//            weakSelf.bgEmptyImg.image = [YiPayWatchManager imageNamed:@"empty_follow_normal"];
//            weakSelf.bgEmptyLab.text = @"主播正在准备中";
//            weakSelf.refreshBtn.hidden = NO;
            
        }
        
    } failure:^(NSError * _Nonnull nullable) {
        if (dataLoadType == DataLoadTypeNews) [weakSelf.tableView.mj_header endRefreshing];
        if (dataLoadType == DataLoadTypeMore) [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView reloadData];
    }];
}
- (UIView *)bgEmptyView {
    if (!_bgEmptyView) {
        _bgEmptyView = [[UIView alloc] initWithFrame:CGRectZero];
        [self.tableView addSubview:_bgEmptyView];
        _bgEmptyView.hidden = YES;
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 210, 166)];
        img.image = [UIImage imageNamed:@"mobile_noLive.8b3d11c"];
        [self.bgEmptyView addSubview:img];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, img.frame.size.height+15, 210, 20)];
        label.text = @"暂无直播";
        label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = RYColorForHex(@"#999DA6");
        [self.bgEmptyView addSubview:label];

        
    }
    return _bgEmptyView;
}
- (void)toCheckIsSuccessCreateCourse:(BOOL)isSuccess
{
    if (isSuccess) {
        UIButton *button1 = (UIButton *)[self.navigationItem.leftBarButtonItems[0] customView];
        UIButton *button2 = (UIButton *)[self.navigationItem.leftBarButtonItems[1] customView];
        button1.selected = NO;
        self.isToday = NO;
        if (button2.tag == 1001) {
            button2.selected = YES;
            self.selectedButton = button2;
            [self setupAllRefreshData];
        }
    }
}

#pragma mark - numberOfRowsInSection
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    cell.shopCart.tag = indexPath.row;
    [cell.shareLink addTarget:self action:@selector(shareLinkAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shopCart addTarget:self action:@selector(shopCartAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.shareLink.tag = indexPath.row;
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ResultModel *model = self.dataArray[indexPath.row];
    if (model.live_status.status == 3) {
        [[ZXMessageCase shareInstace] showMessage:@"该直播已结束"];
        return;
    }
    //获取权限
    [[YouinRTCManager shardManager] getEnterpriseJsonWithId:model.enterprise_id successBloc:^(id  _Nonnull json) {
        self.isAgoraBeauty = [json[@"beauty_filter"] intValue];
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
    SGAuthorization *authorization = [SGAuthorization authorization];
    [authorization AVAuthorizationBlock:^(SGAuthorization * _Nonnull authorization, SGAuthorizationStatus status) {
        if (status == SGAuthorizationStatusSuccess) {
            [self getCourseDetailsWithLiveId:model];
        } else if (status == SGAuthorizationStatusFail) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 有因助手 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alertC animated:YES completion:nil];
            });
        } else {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alertC animated:YES completion:nil];
            });
        }
    }];
}

//- (void)enterpriseJson:(NSDictionary *)enterpriseDict error:(NSError *)error
//{
//    
//    if (enterpriseDict != nil && enterpriseDict.count != 0) {
//        self.isAgoraBeauty = [enterpriseDict[@"beauty_filter"] intValue];
//        NSLog(@"```");
//    }
//}

//是否极限直播
- (void)getCourseDetailsWithLiveId:(ResultModel *)model
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/system/course_details/%@/",HTTPSURL,model.ID];
    NSDictionary *dic = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};
    __weak typeof(self) weakSelf = self;
    [manager GET:urlString parameters:nil headers:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if ([responseObject[@"code"] intValue] == 200) {
            
            if([responseObject[@"result"][@"stream_url_type"] intValue] == 8){
                //声网sdk 获取token
                [weakSelf getAgoraRtcEngineToken:model];
            }else{
                
                [[YouinRTCManager shardManager] loginIn:userInfo[@"username"] password:userInfo[@"password"] callback:^(NSDictionary *success, NSError * _Nullable error) {
                    LiveRoomViewController *vc = [LiveRoomViewController new];
                    vc.roomID = model.ID;
                    vc.token = userInfo[@"token"];
                    vc.isAgoraRtc = NO;
                    vc.version_id = weakSelf.version_id;
                    vc.isAgoraRtcBeauty = weakSelf.isAgoraBeauty;
                    vc.product_count = model.product_count;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }];
            }
            
        }else{
            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}


#pragma mark - 获取声网sdk的token
- (void)getAgoraRtcEngineToken:(ResultModel *)model
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/system/s_wang_rtc_token/",HTTPSURL];
    NSDictionary *dic = @{@"channel_name":model.ID};
    NSString *token = [NSString stringWithFormat:@"JWT %@",dict[@"token"]];
    __weak typeof(self) weakSelf = self;
    [manager GET:urlString parameters:dic headers:@{@"authorization":token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if ([responseObject[@"code"] intValue] == 200) {
            
            [[YouinRTCManager shardManager] loginIn:userInfo[@"username"] password:userInfo[@"password"] callback:^(NSDictionary *success, NSError * _Nullable error) {
                LiveRoomViewController *vc = [LiveRoomViewController new];
                vc.roomID = model.ID;
                vc.token = userInfo[@"token"];
                vc.channelToken = responseObject[@"result"][@"token"];
                vc.channelAppId = responseObject[@"result"][@"SHENG_WANG_APP_ID"];
                vc.product_count = model.product_count;
                vc.isAgoraRtc = true;
                vc.isAgoraRtcBeauty = weakSelf.isAgoraBeauty;
                vc.version_id = weakSelf.version_id;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}


#pragma mark - 分享链接
- (void)shareLinkAction:(UIButton *)sender
{
    self.buttonTag = sender.tag;
    self.resultModel = self.dataArray[sender.tag];
    LiveListShareView *shareView = [[LiveListShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210)];
    shareView.delegate = self;
    [shareView showView];
}

- (void)buttonsBottomAction:(UIButton *)sender
{
    switch (sender.tag) {
        case 100:
        {
            NewRoomEditVController *newRoomVC = [[NewRoomEditVController alloc] init];
            newRoomVC.isEdit = YES;
            newRoomVC.model = self.resultModel;
            newRoomVC.delegate = self;
            [self.navigationController pushViewController:newRoomVC animated:YES];
        }
            break;
        case 101:
        {

            LiveListSignInView *signINView = [[LiveListSignInView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180)];
            signINView.delegate = self;
            [signINView showView];
        }
            break;
        case 102:
        {//分享
            UIPasteboard *pab = [UIPasteboard generalPasteboard];
            NSString *linkStr = [NSString stringWithFormat:@"%@/livestream/watch/?liveid=%@&enterprise_id=%d",self.resultModel.enterprise.domain_url,self.resultModel.ID,self.resultModel.enterprise.enterprise_id];
            
            [pab setString:linkStr];
            
             if (pab != nil) {

                 [[ZXMessageCase shareInstace] showMessage:@"已复制到剪贴板"];
             }
        }
            break;
        case 103:
        {
            [self checkLiveDataWithId:self.resultModel.ID];
        }
            break;
        case 104:
        {
            [RYAlertController showAlertWithTitle:@"温馨提示" message:@"确定要删除此直播间吗" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
                alertMaker.addActionDefaultTitle(@"取消").addActionDefaultTitle(@"确定");
            } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
                if (buttonIndex == 1) {

                    [self deleteLiveRoomWithCourseId:self.resultModel withIndex:self.buttonTag];
                }
            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)checkLiveDataWithId:(NSString *)liveId
{
    LiveStreamingData *liveData = [[LiveStreamingData alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-180)];
    [liveData showView];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@v1/statistics/system/analysis/%@/?&new_shop=1",HTTPSURL,liveId];
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    
    NSString *token = [NSString stringWithFormat:@"JWT %@",dict[@"token"]];
    [manager GET:urlString parameters:nil headers:@{@"authorization":token} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            [liveData liveData:responseObject[@"result"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)LiveSignActions:(UIButton *)sender
{
    if (sender.tag == 200) {
        SignInSetBottomVIew *bottomView = [[SignInSetBottomVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
        [bottomView showView];
    }else{
        NSLog(@"300");
    }
}

#pragma mark - 删除直播间
- (void)deleteLiveRoomWithCourseId:(ResultModel *)model withIndex:(NSInteger)index
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
//    NSDictionary *params = @{@"course_id":course_id};
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/system/del_course/%@/",HTTPSURL,model.ID];
    
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    NSDictionary *dic = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};
    __weak typeof(self) weakSelf = self;
    [manager POST:urlString parameters:nil headers:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if ([responseObject[@"code"] intValue] == 200) {
            [[ZXMessageCase shareInstace] showMessage:@"删除成功!"];
            NSIndexPath *currentIndexPath=[NSIndexPath indexPathForRow:index inSection:0];
            [weakSelf.dataArray removeObjectAtIndex:index];
            [weakSelf.tableView beginUpdates];
            [weakSelf.tableView deleteRowsAtIndexPaths:@[currentIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            [weakSelf.tableView endUpdates];
            [weakSelf.tableView reloadData];
        }else{
            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error");
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - 购物车
- (void)shopCartAction:(UIButton *)sender{
    ResultModel *model = self.dataArray[sender.tag];
//    [self.liveGoodsVC reloadGoodsListWithEnterpriseId:[NSString stringWithFormat:@"%d",model.enterprise.enterprise_id] withLiveId:model.ID];
    // 预加载商品页
    // 商品
    if (self.liveGoodsVC!=nil) {
        [self.liveGoodsVC.view removeFromSuperview];
    }
    self.liveGoodsVC = [LiveGoodsViewController new];
    self.liveGoodsVC.liveId = model.ID;
    self.liveGoodsVC.enterpriseId = [NSString stringWithFormat:@"%d",model.enterprise.enterprise_id];
    self.liveGoodsVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self addChildViewController:self.liveGoodsVC];
    [self.view addSubview:self.liveGoodsVC.view];
    [self.liveGoodsVC didMoveToParentViewController:self];
    self.liveGoodsVC.view.hidden = true;
    [self.liveGoodsVC show];
}
@end
